<?php
namespace app\admin\controller;
use app\admin\model\brand;
use app\admin\model\Gcategory;
use app\admin\model\goods;
use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\facade\View;
use think\Filesystem;

class Spgl extends BaseController
{
    public function goodList(){
        //1接参，过滤
        $data = Request::get('','','trim,htmlspecialchars,strip_tags');

        //2调用模型类取数据
//        $list = \app\admin\model\goods::getGoodsList($data,$data);
        $list = \app\admin\model\goods::getGoodsList($data,$data);

        //3模板赋值
        $sort = Request::get('sort', '', 'trim,htmlspecialchars,strip_tags');
        $get = Request::get('', '', 'trim,htmlspecialchars,strip_tags');
        if ('desc' == $sort) {
            View::assign('flag','↓');
            $get['sort'] = 'asc';
        } elseif ('asc' == $sort) {
            View::assign('flag','↑');
            unset($get['sort']);
        } else {
            $get['sort'] = 'desc';
        }
        View::assign('get',$get);


        $empty = "<tr><td colspan='11'>暂无数据！</td></tr>";
        $fl=Db::table('ecm_gcategory')->field(true)->select();
        View::assign('fl',$fl);
        View::assign('empty',$empty);
        View::assign($data);
        //4模板渲染
        return View::fetch('',['list'=>$list]);
    }

    public function goodAdd()
    {
        $cates = \app\admin\model\Gcategory::getCateList();  //引入分类
        View::assign('cates', $cates);
        $brand = \app\admin\model\brand::BrandList();       //引入品牌
        View::assign('brand', $brand);
        if (Request::isPost()) {
            $postParam = Request::post('', '', 'trim,htmlspecialchars,strip_tags');
            Db::startTrans();
            try{
                validate(\app\admin\validate\goods::class)->check($postParam);
            }catch (\think\exception\ValidateException $e){
                $this->error($e->getMessage());
            }
            try {
                if($_FILES['default_image']['error']!==4){
                    $logo = Request::file('default_image');
                    $postParam['default_image'] = $logo;
                }
                $date = date('Y/m/d').'/'.mt_rand(11,99);
                $savename = \think\facade\Filesystem::disk('public')->putFile('upload'.'/'.$date,$logo,'md5');
                $postParam['default_image'] = str_replace('\\','/',$savename);
            }catch (\think\exception\ValidateException $e){
                $this->error($e->getError());
            }catch (\Exception $e){}

            try{
                $arr=[];
                $image_urls = Request::file('image_url',[]);
                $rule = ['image_url'=>'filesize:204800|fileExt:jpg,png,gif,jpeg|fileMime:image/jpg,image/png,image/gif,image/jpeg'];
                $data = ['image_url'=>$image_urls];
                validate($rule)->check($data);
                foreach($image_urls as $logos){
                    $names[] = \think\facade\Filesystem::disk('public')->putFile( 'upload',$logos);
                }
                $names = implode(',',$names);
                $arr['image_url'] = str_replace('\\','/',$names);
            }catch (\think\exception\ValidateException $e){
                $this->error($e->getError());
            }catch (\Exception $e){}
            $goodsadd = new \app\admin\model\goods();
            $db = $goodsadd->add($postParam);
            if (''!==$db){
                $arr['goods_id'] = $db;
                $img = new \app\admin\model\GoodsImage();
                $a = $img->add($arr);
            }
            if (isset($postParam['qwert'])){
                $url='goodAdd';
                unset($postParam['qwert']);
            }
            if (isset($postParam['qwer'])){
                $url='goodList';
                unset($postParam['qwer']);
            }
            if ($db){
                $this->success("成功",url("{$url}"));
            }else{
                $this->error("失败！原因".$goodsadd->getError());
            }

        } else {
            return View::fetch('spgl/good_add');
        }
    }
    public function goodedit(){
        if (Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            try{
                validate(\app\admin\validate\goods::class)->scene('edit')->check($post);
            }catch (\think\exception\ValidateException $e){
                $this->error($e->getMessage());
            }
            try{
                $default_image = Request::file('default_image','');
                $rule = ['default_image'=>'filesize:204800|fileExt:jpg,png,gif,jpeg'];
                $data = ['default_image'=>$default_image];
                validate($rule)->check($data);
                $savename = \think\facade\Filesystem::putFile('upload', $default_image);
                $post['default_image'] = str_replace('\\', '/', $savename);
            }catch (\think\exception\ValidateException $e){
                $this->error($e->getError());
            }catch (\Exception $e){}
            $get = Request::get('','','trim,htmlspecialchars,strip_tags');

            if (isset($get['id']))  unset($get['id']);

            $goodsObj=new goods();
            $result = $goodsObj->upt($post);
            if ($result){
                $this->success('修改成功',url('goodList',$get));
            }else{
                $this->error('修改失败');
            }
        }else{
            $get = Request::get('','','trim,htmlspecialchars,strip_tags');

            $id = $get['id']??'';
            $goodsObj = goods::find($id);
            $cates = Gcategory::getGcategory();
            View::assign('cates',$cates);
            $brands = Db::name('brand')->field('brand_id,brand_name')->select();
            View::assign('brands',$brands);
            if (empty($goodsObj)){
                $this->error('参数错误',url('goodList'));
            }
            return View::fetch('',$goodsObj->toArray());
        }
    }

    public function del(){
        $del = Request::get("del",'','trim,htmlspecialchars,strip_tags');
        if (''!==$del){
            $rt = goods::destroy(function ($query) use($del){
               $query->where('goods_id','in',$del);
            });
            if ($rt==1){
                $this->success("删除成功",url('goodList'));
            }else{
                $this->error('删除失败');
            }
        }
    }
    public function huishou()  //回收站
    {
        $data = Request::get('','','trim,htmlspecialchars,strip_tags');

        //2调用模型类取数据
//        $list = \app\admin\model\goods::getGoodsList($data,$data);
        $list = \app\admin\model\goods::getGoodsList($data,$data,false,true);

        //3模板赋值
        $sort = Request::get('sort', '', 'trim,htmlspecialchars,strip_tags');
        $get = Request::get('', '', 'trim,htmlspecialchars,strip_tags');
        if ('desc' == $sort) {
            View::assign('flag','↓');
            $get['sort'] = 'asc';
        } elseif ('asc' == $sort) {
            View::assign('flag','↑');
            unset($get['sort']);
        } else {
            $get['sort'] = 'desc';
        }
        View::assign('get',$get);


        $empty = "<tr><td colspan='11'>暂无数据！</td></tr>";
        $fl=Db::table('ecm_gcategory')->field(true)->select();
        View::assign('fl',$fl);
        View::assign('empty',$empty);
        View::assign($data);
        //4模板渲染
        return View::fetch('',['list'=>$list]);
    }
    public function huishoudel()  //回收站 //真实删除
    {
        $getdel = Request::get('','');
        if(array_key_exists('gid',$getdel) && ''!==$getdel['gid']){
            $img = Db::table('ecm_goods')->where('goods_id',$getdel['gid'])->field('default_image')->find();

            try{
                $goods = Goods::destroy($getdel['gid'],true);
            }catch (\Exception $e){}

            if($goods){
                if($getdel['gid']){
                    unset($getdel['gid']);
                }
                try{
                    if($img){
                        unlink($_SERVER['DOCUMENT_ROOT'].'/storage/'.$img['default_image']);
                    }
                }catch (\Exception $e){}

                if(''!==$getdel){
                    echo $this->success('删除成功！',url('huishou',$getdel));
                }else{
                    echo $this->success('删除成功！',url('huishou'));
                }
            }else{
                echo $this->error('删除失败！');
            }


        }else{
            echo $this->error('参数错误！');
        }
    }

    public function recover() //回收站 //数据恢复
    {
        $gid = Request::get('gid','');

        if(''!==$gid){
            $goods = Goods::onlyTrashed()->find($gid);
            $goods->restore();
            if($goods){
                echo $this->success('恢复成功！','huishou');
            }else{
                echo $this->error('恢复失败！');
            }
        }else{
            echo $this->error('参数错误！');
        }
    }

}